import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { randomInt } from 'crypto';
import { sendEmail } from '@/lib/email';

// 生成6位数字验证码
function generateVerificationCode(): string {
  return randomInt(100000, 999999).toString();
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json();
    const { email } = data;
    
    if (!email) {
      return NextResponse.json(
        { success: false, message: '邮箱地址不能为空' },
        { status: 400 }
      );
    }

    // 查找用户
    const user = await prisma.user.findUnique({
      where: { email }
    });

    // 即使用户不存在，也返回成功，以防止枚举攻击
    if (!user) {
      console.log(`重置密码请求：用户 ${email} 不存在`);
      return NextResponse.json({ success: true });
    }

    // 生成6位数字验证码
    const verificationCode = generateVerificationCode();
    const expires = new Date(Date.now() + 600000); // 10分钟后过期

    // 保存验证码
    await prisma.passwordReset.upsert({
      where: { userId: user.id },
      update: {
        token: verificationCode,
        expires
      },
      create: {
        userId: user.id,
        token: verificationCode,
        expires
      }
    });

    // 发送验证码邮件
    await sendEmail({
      to: email,
      subject: '密码重置验证码',
      text: `您的密码重置验证码是：${verificationCode}，此验证码将在10分钟后过期。`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #eaeaea; border-radius: 5px;">
          <h2 style="color: #333; text-align: center;">密码重置验证码</h2>
          <p>您好，</p>
          <p>我们收到了重置您密码的请求。您的验证码是：</p>
          <div style="background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0;">
            ${verificationCode}
          </div>
          <p>此验证码将在10分钟后失效。</p>
          <p>如果您没有请求重置密码，请忽略此邮件。</p>
          <p>谢谢！</p>
          <p style="font-size: 12px; color: #888; margin-top: 30px; text-align: center;">
            此邮件由系统自动发送，请勿回复
          </p>
        </div>
      `
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('发送重置密码邮件失败:', error);
    return NextResponse.json(
      { success: false, message: '发送重置密码邮件失败' },
      { status: 500 }
    );
  }
}

// 用于验证验证码的API端点
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const email = searchParams.get('email');
    const code = searchParams.get('code');
    
    if (!email || !code) {
      return NextResponse.json(
        { success: false, message: '邮箱和验证码必须提供' },
        { status: 400 }
      );
    }
    
    // 查找用户
    const user = await prisma.user.findUnique({
      where: { email },
      include: { passwordReset: true }
    });
    
    if (!user || !user.passwordReset) {
      return NextResponse.json(
        { success: false, message: '无效的邮箱或验证码' },
        { status: 400 }
      );
    }
    
    // 检查验证码是否有效
    if (user.passwordReset.token !== code) {
      return NextResponse.json(
        { success: false, message: '验证码不正确' },
        { status: 400 }
      );
    }
    
    // 检查验证码是否过期
    if (user.passwordReset.expires < new Date()) {
      return NextResponse.json(
        { success: false, message: '验证码已过期，请重新获取' },
        { status: 400 }
      );
    }
    
    // 验证通过
    return NextResponse.json({ success: true, userId: user.id });
    
  } catch (error) {
    console.error('验证码验证失败:', error);
    return NextResponse.json(
      { success: false, message: '验证码验证失败' },
      { status: 500 }
    );
  }
} 